//
//  HEOrgMapViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/26.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOrgMapViewController.h" 
#import "HEOldPelOrgModel.h"
#import "HEOldOrgCell.h"
#import "HEOrgDetailsViewController.h"

@interface HEOrgMapViewController ()<QMUITextFieldDelegate, BMKMapViewDelegate,UITableViewDelegate,UITableViewDataSource,BMKGeoCodeSearchDelegate, BMKLocationManagerDelegate, BMKSuggestionSearchDelegate, BMKPoiSearchDelegate>

@property(nonatomic,weak) BMKMapView *mapView;//地图 

@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象
@property (nonatomic, strong) BMKUserLocation *userLocation; //当前位置对象

@property(nonatomic,weak) GDTableView *tableView;

@property(nonatomic,strong) NSMutableArray *dataList;//信息

@property (nonatomic, assign) NSIndexPath *selectIndex;//单选，当前选中的行
@property (nonatomic, strong) CLLocationManager *sysLocManager;

@property (nonatomic, assign) BOOL hasReqGeo;
@property (nonatomic, strong) QMUITextField *searchTF;

@property (nonatomic, assign) CLLocationCoordinate2D currentSelectLoc;
@property (nonatomic, strong) BMKLocation *courrentLoc;
@property(nonatomic,strong) NSMutableArray *annoArr;// 标注



@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation HEOrgMapViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.mapView viewWillAppear];
    self.mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil; // 不用时，置nil
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"机构地图";
    
    _dataList = @[].mutableCopy;
    _annoArr = @[].mutableCopy;
    
    _pageNum = 1;
    _pageSize = 20;
    self.isFromHeadRefresh = YES;
 
    [self requestWhenInUseAuthorization];
    
    
    [self setupMapView];
    [self setupSerachUI];
    [self startlocation];
    
    [self setCustomTableView:_tableView];
     
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:KChangeFontNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KChangeFontNotification object:nil];
}

- (void)refresh {
    [self.tableView reloadData];
}

-(void)requestWhenInUseAuthorization {
    if (![self getUserLocationAuth]) {
         if ([self.sysLocManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.sysLocManager requestWhenInUseAuthorization];
        }
    }
}


- (BOOL)getUserLocationAuth {
    BOOL result = NO;
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined: //用户没有选择是否要使用定位服务（弹框没选择，或者根本没有弹框）
            break;
        case kCLAuthorizationStatusRestricted: //定位服务授权状态受限制，可能由于活动限制了定位服务，并且用户不能改变当前的权限，这个状态有可能不是用户拒绝的，但是也有可能是用户拒绝的
            break;
        case kCLAuthorizationStatusDenied: //用户在设置中关闭定位功能，或者用户明确的在弹框之后选择禁止定位
            [Dialog toastBottom:@"请前往设置开启定位权限~"];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            result = YES;
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            result = YES;
            break;
            
        default:
            break;
    }
    return result;
}

- (CLLocationManager *)sysLocManager {
    if (!_sysLocManager) {
        _sysLocManager = [[CLLocationManager alloc] init];
        _sysLocManager.desiredAccuracy = kCLLocationAccuracyBest;
        _sysLocManager.distanceFilter = kCLLocationAccuracyHundredMeters;
    }
    return _sysLocManager;
}

- (void)setupSerachUI {
    
    UIView *serchWarp = [UIView new];
    [self.view addSubview:serchWarp];
    
    serchWarp.qmui_borderPosition = QMUIViewBorderPositionBottom | QMUIViewBorderPositionTop;
    serchWarp.qmui_borderWidth = 1;
    serchWarp.qmui_borderColor = CSplitLineColor;
    
    [serchWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_mapView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_offset(60);
    }];
    
    // 输入框
    QMUITextField *searchTF = [[QMUITextField alloc] init];
    searchTF.backgroundColor = KHexColor(@"F1F3F8");
    searchTF.layer.cornerRadius = 20;
    searchTF.font = DYFont(16);
    searchTF.placeholder = @"搜索地点";
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.delegate = self;
    _searchTF = searchTF;
    [serchWarp addSubview:searchTF];
    
    UIView *leftWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 18)];
    UIImageView *leftIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"search")];
    leftIcon.frame = CGRectMake(20, 0, 18, 18);
    [leftWarp addSubview:leftIcon];
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.leftView = leftWarp;
    
    // 搜索按钮
    UIView *rightWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 70, 40)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 70, 40);
    [btn setTitle:@"搜索" forState:UIControlStateNormal];
    btn.titleLabel.font = DYFont(16);
    btn.backgroundColor = CNavBgColor;
    [btn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [btn hg_setCornerOnRightWithRadius:20];
    [rightWarp addSubview:btn];
    searchTF.rightViewMode = UITextFieldViewModeAlways;
    searchTF.rightView = rightWarp;
    [btn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(serchWarp).mas_offset(10);
        make.left.equalTo(serchWarp.mas_left).mas_offset(10);
        make.right.equalTo(serchWarp.mas_right).mas_offset(-10);
        make.bottom.equalTo(serchWarp).mas_offset(-10);
    }];
    
//    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(serchWarp);
//        make.right.equalTo(serchWarp.mas_right);
//        make.bottom.equalTo(serchWarp);
//        make.width.mas_offset(80);
//    }];
//
    
    GDTableView *tableView = [[GDTableView alloc]initWithFrame:CGRectMake(0, kScreenHeight * 0.4 + 60, KScreenWidth, kScreenHeight  - kScreenHeight * 0.4 - 60) style:UITableViewStylePlain];
    self.tableView = tableView;
    _tableView.separatorColor = CSplitLineColor;
    _tableView.scrollsToTop = YES;
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
    tableView.delegate = self;
    tableView.dataSource = self;
    
    __weak __typeof(&*self)weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        weakSelf.isFromHeadRefresh = YES;
        weakSelf.pageNum = 1;
        
        [weakSelf loadData];
    }];

    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        weakSelf.isFromHeadRefresh = NO;
        weakSelf.pageNum += 1;
        [weakSelf loadData];
    }];
    
    [tableView registerClass:[HEOldOrgCell class] forCellReuseIdentifier: KHEOldOrgCell];
    [self.view addSubview:tableView];
}

- (void)setupMapView{
    BMKMapView *mapView = [[BMKMapView alloc]init];
    [self.view addSubview:mapView];
    [mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.height.offset(kScreenHeight * 0.4);
    }];
    self.mapView = mapView;
    //设置mapView的代理
    _mapView.delegate = self;
    
    //添加返回定位点按钮代码

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.backgroundColor = KWhiteColor;
    [backBtn setImage:[UIImage imageNamed:@"zoom_location"] forState:UIControlStateNormal];
    backBtn.frame =CGRectMake(10, self.view.frame.size.height-90, 40, 40);
    [self.mapView addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_mapView).offset(-15);
        make.right.equalTo(_mapView).offset(-15);
        make.width.height.offset(35);
    }];
    [backBtn hg_setAllCornerWithCornerRadius:8]; 
    [backBtn addTarget:self action:@selector(comeBackLocation) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *button = [[UIButton alloc]init];
    [button setImage:[UIImage imageNamed:@"location_pic"] forState:UIControlStateNormal];
    [mapView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(mapView);
    }];
    
    self.mapView.showsUserLocation = YES;//显示定位图层
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    self.mapView.zoomLevel = 14;//地图显示的级别
}

- (void)comeBackLocation {
    [self.mapView setCenterCoordinate:self.userLocation.location.coordinate animated:YES];

}

- (void)startlocation {
    //开启定位服务
    [self.locationManager startUpdatingLocation];
}

- (void)searchClick {
    [self loadData];
}
 

#pragma mark - UITableViewDelegate && dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HEOldOrgCell *cell = [tableView dequeueReusableCellWithIdentifier: KHEOldOrgCell];
    cell.model = self.dataList[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: KHEOldOrgCell cacheByIndexPath:indexPath configuration:^(HEOldOrgCell *cell) {
        cell.model = self.dataList[indexPath.row];
     }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    HEOldPelOrgModel *model = self.dataList[indexPath.row];
    HEOrgDetailsViewController *vc = [HEOrgDetailsViewController new];
    vc.orgId = model.id;
    [self.navigationController pushViewController:vc animated:YES];
 }
 
#pragma mark - baidu map
#pragma mark - BMKMapViewDelegate
 
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    BMKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center = centerCoordinate;
    _currentSelectLoc = centerCoordinate;

    [self.tableView.mj_header beginRefreshing];
}

- (void)loadData {
    if ([DYTools isBlankString: _searchTF.text]) {

        [self loadOrgList];
    }else {
        [self loadOrgListByName];
    }
}

- (void)loadOrgList {
  
    NSMutableDictionary *req = @{}.mutableCopy;
    [req setValue:[NSNumber numberWithDouble:_currentSelectLoc.latitude] forKey:@"latitude"];
    [req setValue:[NSNumber numberWithDouble:_currentSelectLoc.longitude] forKey:@"longitude"];
 
     [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KoldpeopleScope parameters:req success:^(id  _Nonnull responseObject) {

         [self.tableView.mj_header endRefreshing];
         [self.tableView.mj_footer endRefreshing];
         
        if (self.isFromHeadRefresh) {
            [self.dataList removeAllObjects];
        }else {
            return;
        }

        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [self.dataList addObjectsFromArray:[HEOldPelOrgModel mj_objectArrayWithKeyValuesArray:response.data]];
        [self.tableView reloadData];
         [self createAnnotation];

        if (self.dataList.count == 0) {
            [self showEmpty];
        }
    
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)loadOrgListByName {
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = _pageNum;
    req.pageSize = _pageSize;
    [req addParmas: [NSNumber numberWithDouble:_currentSelectLoc.latitude] key:@"latitude"];
    [req addParmas: [NSNumber numberWithDouble:_currentSelectLoc.longitude] key:@"longitude"];
    [req addParmas: _searchTF.text key:@"keyword"];

     [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:Koldpeople_name parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        if (self.isFromHeadRefresh) {
            [self.dataList removeAllObjects];
        }

        HEPageResponse *response = [HEPageResponse mj_objectWithKeyValues:responseObject];
        [self.dataList addObjectsFromArray:[HEOldPelOrgModel mj_objectArrayWithKeyValuesArray:response.data.list]];
        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
         
         [self createAnnotation];

        if (self.dataList.count == 0) {
            [self showEmpty];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
 
#pragma mark - TextFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
 
    return YES;
}

- (void)createAnnotation {
    
    [_mapView removeAnnotations:_annoArr];
    [_annoArr removeAllObjects];
    for (HEOldPelOrgModel *model in _dataList) {
        //初始化一个点的注释
        BMKPointAnnotation * annotoation = [[BMKPointAnnotation alloc] init];
        annotoation.coordinate = CLLocationCoordinate2DMake(model.latitude, model.longitude);
        annotoation.title = model.company_name;
        [_annoArr addObject:annotoation];
    }
    
    //将标注加在地图上
    [_mapView addAnnotations: _annoArr];

}


#pragma mark -- BMKMapViewDelegate
/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{

      //如果是注释点
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
    
        //根据注释点,创建并初始化注释点视图
        BMKPinAnnotationView  *newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"an"];
        newAnnotation.image = IMAGE_NAMED(@"gpers_icon");
        newAnnotation.animatesDrop = YES;
        return newAnnotation;
    }
    return nil;
}
 

#pragma mark - 定位 BMKLocationManagerDelegate
/**
 @brief 当定位发生错误时，会调用代理的此方法
 @param manager 定位 BMKLocationManager 类
 @param error 返回的错误，参考 CLError
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didFailWithError:(NSError * _Nullable)error {
    NSLog(@"定位失败");
}

/**
 @brief 该方法为BMKLocationManager提供设备朝向的回调方法
 @param manager 提供该定位结果的BMKLocationManager类的实例
 @param heading 设备的朝向结果
 */
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateHeading:(CLHeading *)heading {
    if (!heading) {
        return;
    }
    NSLog(@"用户方向更新");
    
    self.userLocation.heading = heading;
    [_mapView updateLocationData:self.userLocation];
}

/**
 @brief 连续定位回调函数
 @param manager 定位 BMKLocationManager 类
 @param location 定位结果，参考BMKLocation
 @param error 错误信息。
 */
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateLocation:(BMKLocation *)location orError:(NSError *)error {
    if (error) {
        NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
    }
    if (!location) {
        return;
    }
    
    self.userLocation.location = location.location;
    //实现该方法，否则定位图标不出现
    [_mapView updateLocationData:self.userLocation];
    _courrentLoc = location;

    if (!_hasReqGeo) {
        _currentSelectLoc = _userLocation.location.coordinate;
        _hasReqGeo = YES;

        [self loadData];
    }
}


#pragma mark - lazyLoad

- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化BMKLocationManager类的实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置定位管理类实例的代理
        _locationManager.delegate = self;
        //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设定定位精度，默认为 kCLLocationAccuracyBest
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //指定定位是否会被系统自动暂停，默认为NO
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        /**
         是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
         设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
         由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
         */
        _locationManager.allowsBackgroundLocationUpdates = NO;
        /**
         指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
         注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
         后开始计算。
         */
        _locationManager.locationTimeout = 10;
    }
    return _locationManager;
}

- (BMKUserLocation *)userLocation {
    if (!_userLocation) {
        //初始化BMKUserLocation类的实例
        _userLocation = [[BMKUserLocation alloc] init];
    }
    return _userLocation;
}
 

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

 
@end
